package com.opener.web.service.file.impl;

import com.opener.common.utils.URLUTF8Encoder;
import com.opener.web.service.file.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 *
 * @author baboy
 * @date 06/06/2017
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${storage.path.tmp}")
    private String storageTmpPath;
    @Value("${storage.path.dir}")
    private String storagePath;

    @Value("${nginx.download.path.prefix}")
    private String nginxDoanloadPathPrefx;

    @Override
    public File saveTmpFile(String fn, InputStream is) {
        String fp = storageTmpPath+"/"+fn;
        File f = new File(fp);
        try {
            File dir = f.getParentFile();
            if(!dir.exists()){
                dir.mkdirs();
            }
            if(!f.exists()){
                f.createNewFile();
            }
            FileOutputStream os = new FileOutputStream(f,true);
            byte[] buf = new byte[1024*500];
            int len = 0;
            while ((len = is.read(buf)) >= 0){
                os.write(buf,0,len);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return f;
    }

    @Override
    public boolean moveFile(File srcFile, File destFile) {
        boolean ret = srcFile.renameTo(destFile);
        if (!ret){
            try {
                int n = FileCopyUtils.copy(srcFile, destFile);
                if (n>0){
                    srcFile.delete();
                    ret = true;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return  ret;
    }

    @Override
    public File saveFile(String srcFp, String dir) {
        String dstFn = UUID.randomUUID().toString();
        String[] a = srcFp.split(".");
        if(a.length>1){
            String ext = a[a.length-1];
            dstFn = dstFn + "." + ext;
        }
        File destFile = new File(dir+"/"+dstFn);
        File srcFile = new File(storageTmpPath + "/"+srcFp);
        if (srcFile.exists()){
            boolean ret = moveFile(srcFile, destFile);
            if (ret){
                return destFile;
            }
        }
        return null;
    }

    @Override
    public File saveFile(File srcFile, String destFp) {
        File destFile = new File(storagePath + "/" + destFp);
        File destDir = destFile.getParentFile();
        if(!destDir.exists()){
            destDir.mkdirs();
        }
        boolean ret = moveFile(srcFile, destFile);
        return ret ? destFile : null;
    }

    @Override
    public File getTmpFile(String fn) {
        String fp = storageTmpPath+"/"+fn;
        File f = new File(fp);
        return f;
    }
    @Override
    public File getStorageFile(String fn){
        String fp = storagePath+"/"+fn;
        File f = new File(fp);
        return f;
    }
    @Override
    public boolean setNginxFileDownloadHeader(HttpServletResponse res, String fn, String fp, String mimeType){
        if(fp!=null){
            String nginxFp = nginxDoanloadPathPrefx+"/"+fp;
            res.addHeader("Content-Disposition","attachment; filename="+ URLUTF8Encoder.encode(fn));
            res.addHeader("X-Accel-Redirect",nginxFp);
            res.addHeader("Content-Type",mimeType);
            return true;
        }
        return false;
    }
}
